package com.sheep.juc;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author wangze
 * @date 2020-10-22 9:34.
 **/
public class CachedData {
	Object data;
	final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
	volatile boolean cacheValid;

	void processData() {
		rwl.readLock().lock();
		System.out.println(Thread.currentThread().getName()+"获取了读锁"+Thread.currentThread().getState().name());

		if (!cacheValid) {
			rwl.readLock().unlock();
			System.out.println(Thread.currentThread().getName()+"释放了读锁----11"+"    ");
			rwl.writeLock().lock();
			System.out.println(Thread.currentThread().getName()+"获取了写锁");
			System.out.println("queenlength"+rwl.getQueueLength()+"getReadHoldCount" +rwl.getReadHoldCount()+"getReadLockCount"+rwl.getReadLockCount());
			try {
				if (!cacheValid) {
					System.out.println(Thread.currentThread().getName()+"---------------我改变了数据----------------------");
					data = "测试"+System.currentTimeMillis();
					cacheValid = true;
				}
				System.out.println(Thread.currentThread().getName()+"重新获取了读锁");
				rwl.readLock().lock();
			} finally {
				rwl.writeLock().unlock();
			}
		}

		try {
			use(data);
		} finally {
			rwl.readLock().unlock();
		}


	}


	void use(Object data) {
		System.out.println(data.toString());
	}
}
